#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

// 父进程写，子进程读

int main()
{
    int fds[2] = {0};
    int n = pipe(fds);  //创建好管道文件
    assert(n == 0);

    pid_t id = fork();
    assert(id >= 0);

    if(id == 0)
    {
        //子进程读，关闭写端
        close(fds[1]);
        
        while(true)
        {
            char buffer[1024] = {0};
            int s = read(fds[0],buffer,sizeof(buffer)-1);
            if(s > 0)
            {
                buffer[s] = 0;
                cout << "子进程接收到父进程信息:" << buffer << endl;
            }
            else if(s == 0)
            {
                cout << "父进程写端关闭，子进程无法接收信息" << endl;
                break;
            }
        }

        close(fds[0]);
        exit(0);
    }
    else 
    {
        //父进程写，关闭读端
        close(fds[0]);
        int cnt = 1;
        while(true)
        {
            char buffer[1024] = {0};
            snprintf(buffer,sizeof(buffer),"i am father[%d]",cnt++);
            write(fds[1],buffer,strlen(buffer));
            sleep(1);
        }

        close(fds[1]);
        int ret = waitpid(id,nullptr,0);
        assert(ret == id);
    }
    return 0;
}